import { Component, OnInit } from '@angular/core';
import { AlertController, ModalController } from '@ionic/angular';
import { debounce, find, toNumber } from 'lodash';
import { pb } from 'src/pb';
import { CallService } from '../call.service';
import { SelectPathPage } from '../select-path/select-path.page';


@Component({
  selector: 'app-hash',
  templateUrl: './hash.page.html',
  styleUrls: ['./hash.page.scss'],
})
export class HashPage implements OnInit {
  hash: any[] = [];
  text = '';
  file = '';
  change: any;
  constructor(
    private callService: CallService,
    private modalCtrl: ModalController,
    private alertCtrl: AlertController,
  ) {
    this.change = debounce(this.sum, 500);
    for (const t in pb.HashType) {
      if (isNaN(toNumber(t))) {
        this.hash.push({
          type: t,
          sum: '',
        });
      }
    }
  }

  async select() {
    const modal = await this.modalCtrl.create({
      component: SelectPathPage,
      componentProps: { path: '' },
    });
    await modal.present();
    const r = await modal.onDidDismiss();
    if (r.data) {
      const h = await this.callService.call('fileHash', { msg: '生成摘要', def: { md5: 'md5--', sha1: 'sha1--' } }, r.data);
      if (h.error) {
        const alert = await this.alertCtrl.create({
          header: '文件生成摘要异常',
          subHeader: r.data,
          message: h.error,
          buttons: ['关闭']
        });
        await alert.present();
        return;
      }
      for (const t of this.hash) {
        t.sum = h[t.type];
      }
      this.file = r.data;
    }
  }

  async sum() {
    this.file = '';
    for (const t in pb.HashType) {
      if (isNaN(toNumber(t))) {
        const h = find(this.hash, { type: t });
        h.sum = await this.callService.call('hash',
          { def: this.text },
          this.text, t);
      }
    }
  }

  ngOnInit() {
  }

}
